import React, { useState, useRef, useEffect, forwardRef, useImperativeHandle } from 'react'
import { CSSTransition } from 'react-transition-group'
import BScroll from '@better-scroll/core'
import Wheel from '@better-scroll/wheel'
import './index.styl'
import PPPPCCCC from './two-level-address.js'
BScroll.use(Wheel)

var PPPP = PPPPCCCC.map((v) => {
  return v.name
})
var CCCC = PPPPCCCC[0].children.map(v => v.name)

const stopPropagation = (e) => {
  e.stopPropagation()
}

//const pickerData = [YEARS, MONTHS, DAYS]

const TripleColumn = forwardRef((props, ref) => {

  const [pickerData, setPickerData] = useState([PPPP, CCCC])//[省份,区县]
  console.log('======pickerData', pickerData);
  const [visible, setVisible] = useState(false)
  const [selectedIndexPair, setSelectedIndexPair] = useState([0, 0])
  const [selectedText, setSelectedText] = useState('省与市')

  const wrapperRef = useRef(null)
  const scrollRef = useRef([])


  useImperativeHandle(ref, () => ({
    handleShow,
    selectedText
  }));

  useEffect(() => {
    if (visible) {
      const createWheel = (wheelWrapper, i) => {
        if (scrollRef.current[i]) {
          scrollRef.current[i].refresh()
        } else {
          const BS = (scrollRef.current[i] = new BScroll(
            wheelWrapper.children[i],
            {
              wheel: {
                wheelWrapperClass: 'wheel-scroll',
                wheelItemClass: 'wheel-item',
                selectedIndex: selectedIndexPair[i],
              },
              useTransition: true,
              probeType: 3,
            }
          ))

          // < v2.1.0
          BS.on('scrollEnd', (aa) => {
            console.log('BS.getSelectedIndex()', BS.getSelectedIndex())
            const currentSelectedIndexPair = scrollRef.current.map((wheel) =>
              wheel.getSelectedIndex()
            )
            var __year = currentSelectedIndexPair[0]
            var __month = currentSelectedIndexPair[1]
            var __cccc = PPPPCCCC[__year].children.map(v => v.name)
            console.log('======__cccc', __cccc);

            setPickerData([PPPP, __cccc])
          })

        }
      }

      const wrapper = wrapperRef.current
      for (let i = 0; i < pickerData.length; i++) {
        createWheel(wrapper, i)
      }
    }
  }, [visible, selectedIndexPair])
  useEffect(() => {
    if (scrollRef.current[1]) { scrollRef.current[1].refresh() }
  }, [pickerData])
  const handleShow = () => {
    if (visible) {
      return
    }


    setVisible(true)
  }

  const handleHide = () => {
    setVisible(false)
  }

  const handleConfirm = () => {
    scrollRef.current.forEach((wheel) => {
      /*
       * if bs is scrolling, force it stop at the nearest wheel-item
       * or you can use 'restorePosition' method as the below
       */
      wheel.stop()
      /*
       * if bs is scrolling, restore it to the start position
       * it is same with iOS picker and web Select element implementation
       * supported at v2.1.0
       */
      // wheel.restorePosition()
    })
    handleHide()
    const currentSelectedIndexPair = scrollRef.current.map((wheel) =>
      wheel.getSelectedIndex()
    )

    setSelectedIndexPair(currentSelectedIndexPair)
    setSelectedText(
      pickerData
        .map((data, i) => {
          const index = currentSelectedIndexPair[i]
          return `${data[index].text}-${index}`
        })
        .join('__')
    )
    var vv = pickerData
      .map((data, i) => {
        const index = currentSelectedIndexPair[i]
        return data[index]
      })
    //vv形如[2024, 3, 23],代表2024年4月24日,也就是月和日都要加1才是人类认知的日期
    props.onMessage && props.onMessage(vv)
  }

  const handleCancel = () => {
    /*
     * if bs is scrolling, restore it to the start position
     * it is same with iOS picker and web Select element implementation
     * supported at v2.1.0
     */
    scrollRef.current.forEach((wheel) => {
      wheel.restorePosition()
    })
    handleHide()
  }
  return (
    <div className="container view">
      {/* <div className="container-btn" onClick={handleShow}>
        {selectedText}
      </div> */}
      <section

        className="picker-fade"

        style={{ display: visible ? 'block' : 'none' }}
      >
        <div
          style={{ display: 'block' }}
          className="picker"
          onClick={handleCancel}
        >
          <section className="picker-move" style={{ display: visible ? 'block' : 'none' }}>
            <div className="picker-panel" onClick={stopPropagation}>
              <div className="picker-choose border-bottom-1px">
                <span className="cancel" onClick={handleCancel}>
                  取消
                </span>
                <span className="confirm" onClick={handleConfirm}>
                  确定
                </span>
                <h1 className="picker-title"></h1>
              </div>
              <div className="picker-content">
                <div className="mask-top border-bottom-1px"></div>
                <div className="mask-bottom border-top-1px"></div>
                <div className="wheel-wrapper" ref={wrapperRef}>
                  {pickerData.map((data, index) => (
                    <div className="wheel" key={index}>
                      <ul className="wheel-scroll">
                        {data.map((item, index) => (
                          <li key={'a' + index} className="wheel-item">
                            {item}
                          </li>
                        ))}
                      </ul>
                    </div>
                  ))}
                </div>
              </div>
              <div className="picker-footer"></div>
            </div>
          </section>
        </div>
      </section>
    </div>
  )

})

export default TripleColumn
